package com.cdy.jxc_project.config;

import com.cdy.jxc_project.utils.MysqlRealm;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/*
 * @Project:jxc_project
 * @Author:cdy(缘生)
 * @Motto:放下杂念,只为迎接明天更好的自己
 * @Date:2023/5/8 14:37
 * */
@Configuration
public class ShiroConfig {
    /**
     * anon: 无需认证就可以访问
     * authc: 必须认证了才能访问
     * user: 必须拥有 记住我功能 才能用
     * perms: 拥有对某个资源的权限才能访问
     * role: 拥有某个角色权限才能访问
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager());
        //告知过滤器，需要去拦截那些请求，放行那些请求
          Map<String,String> maps = new HashMap<>();
     /* maps.put("/login/**","anon");//放行,允许匿名访问
        maps.put("/user/**","authc");//必须认证之后，才能访问，必须登录成功之后，才能访问
        maps.put("/login/main","authc");//主页面一定要认证之后才能使用
      设置都需要认证之后才能访问
        maps.put("/dept/**","authc");
        maps.put("/salary/**","authc");
      所有请求都需要拦截
        maps.put("/**","authc");*/
        maps.put("/admin/**","anon");
        maps.put("/doc.html","anon");
        maps.put("/goodsType/**","anon");
        //需要添加角色信息来判断
        shiroFilterFactoryBean.setFilterChainDefinitionMap(maps);
        //直接拦截到前端登录页面
        //shiroFilterFactoryBean.setLoginUrl("http://localhost:8080/#/");
        //处理md5加密
        return shiroFilterFactoryBean;
    }
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(mysqlRealm());
        return defaultWebSecurityManager;
    }
//  添加md5加密算法
    @Bean
    public Realm mysqlRealm(){
        MysqlRealm mysqlRealm = new MysqlRealm();
        //md5加密算法
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        //设置用户的安全凭证
        mysqlRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return mysqlRealm;
    }
}
